document.addEventListener('DOMContentLoaded',function () {
    const videoPlayer = document.getElementById('videoPlayer');
    const videoUrl = document.getElementById('videoUrl');
    const playButton = document.getElementById('playButton');
    const formatSelector = document.getElementById('formatSelector');
    const speedSelector = document.getElementById('speedSelector');
    const localFileBtn = document.getElementById('localFileBtn');
    const fileInput = document.getElementById('fileInput');
    const fullscreenBtn = document.getElementById('fullscreenBtn');
    const selectDirBtn = document.getElementById('selectDirBtn');
    const dirInput = document.getElementById('dirInput');
    const directoryList = document.getElementById('directoryList');
    const pathNavigator = document.getElementById('pathNavigator');
    const listViewBtn = document.getElementById('listViewBtn');
    const gridViewBtn = document.getElementById('gridViewBtn');
    const tabButtons = document.querySelectorAll('.tab-btn');
    const tabPanels = document.querySelectorAll('.tab-panel');
    const resizer = document.getElementById('resizer');
    const sidebar = document.querySelector('.sidebar');
    const container = document.querySelector('.container');
    let isResizing = false;

    let hls = null;
    let currentVideo = null;
    let fileTree = {};
    let currentPath = [];
    let currentViewMode = 'list'; // 'list' 或 'grid'

    // 支持的视频格式
    const videoFormats = ['.mp4','.m3u8','.webm','.mkv','.avi','.mov'];

    // 缩略图缓存
    const thumbnailCache = new Map();

    function isVideoFile(filename) {
        return videoFormats.some(format => filename.toLowerCase().endsWith(format));
    }

    function formatTime(seconds) {
        const minutes = Math.floor(seconds / 60);
        seconds = Math.floor(seconds % 60);
        return `${minutes}:${seconds.toString().padStart(2,'0')}`;
    }

    function updatePathNavigator() {
        pathNavigator.innerHTML = '';

        // 添加根目录
        const rootLink = document.createElement('span');
        rootLink.className = 'path-part';
        rootLink.textContent = '根目录';
        rootLink.addEventListener('click',() => navigateToPath([]));
        pathNavigator.appendChild(rootLink);

        // 添加路径分隔符和子目录
        currentPath.forEach((part,index) => {
            const separator = document.createElement('span');
            separator.className = 'path-separator';
            separator.textContent = ' / ';
            pathNavigator.appendChild(separator);

            const pathPart = document.createElement('span');
            pathPart.className = 'path-part';
            pathPart.textContent = part;
            pathPart.addEventListener('click',() => navigateToPath(currentPath.slice(0,index + 1)));
            pathNavigator.appendChild(pathPart);
        });
    }

    function navigateToPath(path) {
        currentPath = path;
        updatePathNavigator();
        displayCurrentDirectory();
    }

    function getDirectoryContent(path) {
        let current = fileTree;
        for (const part of path) {
            current = current[part].items;
        }
        return current;
    }

    // 生成视频缩略图
    async function generateThumbnail(videoUrl) {
        if (thumbnailCache.has(videoUrl)) {
            return thumbnailCache.get(videoUrl);
        }

        return new Promise((resolve) => {
            const video = document.createElement('video');
            video.src = videoUrl;
            video.currentTime = 1; // 跳到第1秒
            video.addEventListener('loadeddata',() => {
                const canvas = document.createElement('canvas');
                canvas.width = 200;
                canvas.height = 150;
                const ctx = canvas.getContext('2d');
                ctx.drawImage(video,0,0,canvas.width,canvas.height);
                const thumbnailUrl = canvas.toDataURL();
                thumbnailCache.set(videoUrl,thumbnailUrl);
                resolve(thumbnailUrl);
            });
            video.addEventListener('error',() => {
                resolve(null);
            });
        });
    }

    function displayCurrentDirectory() {
        directoryList.innerHTML = '';
        const content = getDirectoryContent(currentPath);

        // 设置容器类名
        directoryList.className = `directory-list ${currentViewMode === 'grid' ? 'grid-view' : ''}`;

        // 添加返回上级目录按钮
        if (currentPath.length > 0) {
            const backItem = document.createElement('div');
            backItem.className = 'directory-item';
            if (currentViewMode === 'grid') {
                const iconDiv = document.createElement('div');
                iconDiv.className = 'item-icon';
                const icon = document.createElement('i');
                icon.className = 'back-icon';
                iconDiv.appendChild(icon);
                backItem.appendChild(iconDiv);

                const nameDiv = document.createElement('div');
                nameDiv.className = 'item-name';
                nameDiv.textContent = '返回上级';
                backItem.appendChild(nameDiv);
            } else {
                const icon = document.createElement('i');
                icon.className = 'back-icon';
                backItem.appendChild(icon);

                const nameSpan = document.createElement('span');
                nameSpan.textContent = '返回上级';
                backItem.appendChild(nameSpan);
            }
            backItem.addEventListener('click',() => {
                navigateToPath(currentPath.slice(0,-1));
            });
            directoryList.appendChild(backItem);
        }

        // 显示文件和文件夹，按时间降序排序
        Object.entries(content)
            .map(([name,content]) => ({
                name,
                content,
                isDirectory: content.isDirectory,
                lastModified: content.lastModified || 0
            }))
            .sort((a,b) => {
                // 首先按类型排序（文件夹在前）
                if (a.isDirectory !== b.isDirectory) {
                    return a.isDirectory ? -1 : 1;
                }
                // 然后按修改时间降序排序
                return b.lastModified - a.lastModified;
            })
            .forEach(async ({ name,content }) => {
                const isDirectory = content.isDirectory;
                const item = document.createElement('div');
                item.className = 'directory-item';

                if (currentViewMode === 'grid') {
                    const iconDiv = document.createElement('div');
                    iconDiv.className = 'item-icon';

                    if (!isDirectory && isVideoFile(name)) {
                        try {
                            const thumbnailUrl = await generateThumbnail(content.url);
                            if (thumbnailUrl) {
                                const img = document.createElement('img');
                                img.src = thumbnailUrl;
                                iconDiv.appendChild(img);
                            } else {
                                const icon = document.createElement('i');
                                icon.className = 'video-icon';
                                iconDiv.appendChild(icon);
                            }
                        } catch (error) {
                            const icon = document.createElement('i');
                            icon.className = 'video-icon';
                            iconDiv.appendChild(icon);
                        }
                    } else {
                        const icon = document.createElement('i');
                        icon.className = isDirectory ? 'folder-icon' : 'video-icon';
                        iconDiv.appendChild(icon);
                    }
                    item.appendChild(iconDiv);

                    const nameDiv = document.createElement('div');
                    nameDiv.className = 'item-name';
                    nameDiv.textContent = name;

                    // 添加修改时间
                    const timeDiv = document.createElement('div');
                    timeDiv.className = 'item-time';
                    const date = new Date(content.lastModified);
                    timeDiv.textContent = date.toLocaleDateString() + ' ' + date.toLocaleTimeString();

                    item.appendChild(nameDiv);
                    item.appendChild(timeDiv);
                } else {
                    const icon = document.createElement('i');
                    icon.className = isDirectory ? 'folder-icon' : 'video-icon';
                    item.appendChild(icon);

                    const nameSpan = document.createElement('span');
                    nameSpan.textContent = name;
                    item.appendChild(nameSpan);

                    // 添加修改时间
                    const timeSpan = document.createElement('span');
                    timeSpan.className = 'item-time';
                    const date = new Date(content.lastModified);
                    timeSpan.textContent = date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
                    item.appendChild(timeSpan);
                }

                if (isDirectory) {
                    item.addEventListener('click',() => {
                        navigateToPath([...currentPath,name]);
                    });
                } else if (isVideoFile(name)) {
                    item.addEventListener('click',() => {
                        initializePlayer(content.url,name.endsWith('.m3u8') ? 'm3u8' : 'mp4');
                    });
                }

                directoryList.appendChild(item);
            });
    }

    function buildFileTree(files) {
        const tree = {};
        files.forEach(file => {
            // 使用HTML5 File API
            const url = URL.createObjectURL(file);
            const parts = file.webkitRelativePath.split('/');
            let current = tree;

            // 构建目录结构
            for (let i = 0; i < parts.length - 1; i++) {
                if (!current[parts[i]]) {
                    current[parts[i]] = {
                        isDirectory: true,
                        lastModified: file.lastModified,
                        items: {}
                    };
                }
                current = current[parts[i]].items;
            }

            // 添加文件
            const fileName = parts[parts.length - 1];
            if (isVideoFile(fileName)) {
                current[fileName] = {
                    url: url,
                    lastModified: file.lastModified,
                    size: file.size,
                    type: file.type,
                    name: fileName
                };
            }
        });
        return tree;
    }

    // 本地文件处理
    localFileBtn.addEventListener('click',function () {
        fileInput.click();
    });

    fileInput.addEventListener('change',function () {
        const file = this.files[0];
        if (file) {
            const url = URL.createObjectURL(file);
            const ext = file.name.split('.').pop().toLowerCase();
            const format = ext === 'm3u8' ? 'm3u8' : 'mp4';
            formatSelector.value = format;
            initializePlayer(url,format,0);
        }
    });

    // 选择目录
    selectDirBtn.addEventListener('click',() => {
        dirInput.click();
    });

    dirInput.addEventListener('change',function () {
        const files = Array.from(this.files);
        if (files.length > 0) {
            fileTree = buildFileTree(files);
            currentPath = [];
            updatePathNavigator();
            displayCurrentDirectory();
        }
    });

    function initializePlayer(url,format,startTime = 0) {
        if (hls) {
            hls.destroy();
        }

        currentVideo = {
            url: url,
            format: format,
            name: url.split('/').pop() || '未命名视频',
            currentTime: startTime
        };

        if (format === 'm3u8' && !url.startsWith('blob:')) {
            if (Hls.isSupported()) {
                hls = new Hls();
                hls.loadSource(url);
                hls.attachMedia(videoPlayer);
                hls.on(Hls.Events.MANIFEST_PARSED,function () {
                    videoPlayer.currentTime = startTime;
                    videoPlayer.play();
                });
            } else if (videoPlayer.canPlayType('application/vnd.apple.mpegurl')) {
                videoPlayer.src = url;
                videoPlayer.addEventListener('loadedmetadata',function () {
                    videoPlayer.currentTime = startTime;
                    videoPlayer.play();
                });
            } else {
                alert('您的浏览器不支持 HLS 格式视频播放');
            }
        } else {
            videoPlayer.src = url;
            videoPlayer.currentTime = startTime;
            videoPlayer.play();
        }
    }

    playButton.addEventListener('click',function () {
        const url = videoUrl.value.trim();
        if (!url) {
            alert('请输入视频 URL');
            return;
        }
        initializePlayer(url,formatSelector.value);
    });

    fullscreenBtn.addEventListener('click',function () {
        if (!document.fullscreenElement) {
            videoPlayer.requestFullscreen();
        } else {
            document.exitFullscreen();
        }
    });

    speedSelector.addEventListener('change',function () {
        videoPlayer.playbackRate = parseFloat(this.value);
    });

    // 标签页切换
    tabButtons.forEach(button => {
        button.addEventListener('click',() => {
            const targetTab = button.dataset.tab;

            // 更新按钮状态
            tabButtons.forEach(btn => btn.classList.remove('active'));
            button.classList.add('active');

            // 更新面板显示
            tabPanels.forEach(panel => {
                panel.classList.remove('active');
                if (panel.id === `${targetTab}Panel`) {
                    panel.classList.add('active');
                }
            });
        });
    });

    // 视图切换按钮状态更新
    function updateViewButtons() {
        listViewBtn.classList.toggle('active',currentViewMode === 'list');
        gridViewBtn.classList.toggle('active',currentViewMode === 'grid');
    }

    // 切换视图模式
    function switchViewMode(mode) {
        currentViewMode = mode;
        displayCurrentDirectory();
        updateViewButtons();
    }

    // 视图切换按钮事件监听
    listViewBtn.addEventListener('click',() => switchViewMode('list'));
    gridViewBtn.addEventListener('click',() => switchViewMode('grid'));

    // 初始化时设置按钮状态
    updateViewButtons();

    // 分隔栏拖动功能
    resizer.addEventListener('mousedown',function (e) {
        isResizing = true;
        document.body.classList.add('dragging');
        resizer.classList.add('dragging');
    });

    document.addEventListener('mousemove',function (e) {
        if (!isResizing) return;

        // 计算新的宽度
        const containerRect = container.getBoundingClientRect();
        const newWidth = containerRect.right - e.clientX;

        // 限制最小和最大宽度
        if (newWidth >= 280 && newWidth <= containerRect.width - 400) {
            sidebar.style.width = newWidth + 'px';
        }
    });

    document.addEventListener('mouseup',function () {
        if (!isResizing) return;

        isResizing = false;
        document.body.classList.remove('dragging');
        resizer.classList.remove('dragging');

        // 保存当前宽度设置
        chrome.storage.local.set({
            sidebarWidth: sidebar.style.width
        });
    });

    // 加载保存的宽度设置
    chrome.storage.local.get('sidebarWidth',function (data) {
        if (data.sidebarWidth) {
            sidebar.style.width = data.sidebarWidth;
        }
    });
}); 